import { Component, OnInit } from '@angular/core';
import {ActivatedRoute, Router} from "@angular/router";
import {PublicService} from "../../../services/public.service";
import {EventBusService} from "../../../services/event-bus.service";
import {Message, TreeNode} from "primeng/primeng";
import {InventorymaintenanceService} from "../../inventorymaintenance.service";
import {PUblicMethod} from "../../public/PUblicMethod";

@Component({
  selector: 'app-malfunction-solved-inventory',
  templateUrl: './malfunction-solved-inventory.component.html',
  styleUrls: ['./malfunction-solved-inventory.component.scss']
})
export class MalfunctionSolvedInventoryComponent implements OnInit {

  zh: any;
  sid: string;
  startDealTime = PUblicMethod.formateEnrtyTime(new Date());
  initStatus = '';                       // 故障单状态
  malfNumber = '';                       // 服务单号

  malDepPersonOptions: any = [];         // 分配个人可选数据
  malDepPerson = '';                     // 分配个人

  message: Message[] = [];               // 交互提示弹出框
  msg: Message[] = [];                   // 验证弹出框

  selectedDepartment: TreeNode[] = [];   // 分配至部门
  departementDisplay: boolean;           // 树显示控制
  filesTree4: TreeNode[];                // 树的可选值
  selected: TreeNode[];                  // 树的选中值
  dialogHeader: string;                  // 组织树弹框标题
  currentTreeName: string;               // 当前要加载的树
  selectedMode: string;                  // 树的选择模式


  paper: Object = {
    'sid': '',
    'solve_per': '',
    'solve_per_pid': '',
    'solve_org': '',
    'solve_org_oid': '',
    'reason': '',
    'means': '',
    'finish_time': new Date()
  };

  constructor(private maintenanceService: InventorymaintenanceService,
              private router: Router,
              private publicService: PublicService,
              private activatedRouter: ActivatedRoute,
              private eventBusService: EventBusService) { }

  ngOnInit() {
    this.zh = new PUblicMethod().initZh();
    this.startDealTime = PUblicMethod.formateEnrtyTime(this.activatedRouter.snapshot.paramMap.get('time'));
    console.log(this.activatedRouter.snapshot.paramMap.get('time'));
    this.sid = this.activatedRouter.snapshot.paramMap.get('id');
    this.initStatus = this.activatedRouter.snapshot.paramMap.get('status');
    this.getDepPerson();
    this.departementDisplay = false;
    this.initTrick(this.sid);
    this.maintenanceService.getFlowChart( this.initStatus ).subscribe(res => {
      this.eventBusService.maintenance.next(res);
    });
  }
  initTrick(s) {
    this.maintenanceService.getTrick(s).subscribe(res => {
      console.log(res);
      let data = res['data'];
      if (res['errcode'] === '00000') {
        // this.resObj = data;
        // console.log(this.resObj);
        // this.submmitterTime = this.resObj['assign_time'];
        // this.acceptTime = this.resObj['accept_time'];
        // console.log(this.submmitterTime);
        // console.log(this.acceptTime);
      }else {
        this.message = [];
        this.message.push({severity: 'error', summary: '消息提示', detail: `获取故障单信息失败${res}`});
      }
    });
  }
  // 部门组织树模态框
  showTreeDialog(which: string) {
    this.currentTreeName = which;
    this.selected = [];
    this.filesTree4 = [];
    this.departementDisplay = true;
    switch (which) {
      case 'selectedDepartment':
        this.dialogHeader = '请选择部门';
        this.selectedMode = 'single';
        this.maintenanceService.getDepartmentDatas().subscribe(res => {
          this.filesTree4 = res;
        });
        break;
    }
  }
  // 组织树懒加载
  nodeExpand(event) {
    switch ( this.currentTreeName ) {
      case 'selectedDepartment':
        if (event.node) {
          this.maintenanceService.getDepartmentDatas(event.node.oid, event.node.dep).subscribe(res => {
            event.node.children  = res;
          });
        }
        break;
    }
  }
  nodeSelect(event) {
    console.log(event);
  }
  // 清空组织树选中内容
  clearTreeDialog (which) {
    switch ( which ) {
      case 'selectedDepartment':
        this.selectedDepartment = [];
        this.getDepPerson();
        break;
    }
  }
  // 组织树最后选择
  closeTreeDialog() {
    switch ( this.currentTreeName ) {
      case 'selectedDepartment':
        this.selectedDepartment = this.selected;
        this.getDepPerson(this.selected['oid']);
        break;
    }
    this.departementDisplay = false;
  }
  getDepPerson(oid?) {
    this.publicService.getApprovers(oid).subscribe(res => {
      if (!res) {
        this.malDepPersonOptions = [];
      }else {
        this.malDepPersonOptions = res;
      }
    });
  }
  showError() {
    this.msg = [];
    this.msg.push({severity: 'error', summary: '错误消息提示', detail: '请填写完整表单'});
  }
  submitPost(paper) {
    this.maintenanceService.solveTrick( paper ).subscribe(res => {
      if ( res === '00000' ) {
        this.message = [];
        this.message.push({severity: 'success', summary: '消息提示', detail: '操作成功'});
        window.setTimeout(() => {
          this.router.navigateByUrl('/index/maintenance/malfunctionBase');
        }, 1100);

      }else {
        this.message = [];
        this.message.push({severity: 'error', summary: '消息提示', detail: `操作失败${res}`});
      }
    });
  }
//     故障单解决、保存
  solved() {
    this.paper['solve_org'] = this.selectedDepartment['label'];
    this.paper['solve_org_oid'] = this.selectedDepartment['oid'];
    this.paper['solve_per_pid'] = this.malDepPerson['pid'];
    this.paper['solve_per'] = this.malDepPerson['oid'];
    this.paper['sid'] = this.sid;
    console.log(this.paper);
    if ( !this.paper['sid']
      || !this.paper['solve_per']
      || !this.paper['reason']
      || !this.paper['means']
      || !this.paper['finish_time']
    ) {

      this.showError();
    }else {
      this.submitPost(this.paper);
    }
  }
  save() {
    this.paper['solve_org'] = this.selectedDepartment['label'];
    this.paper['solve_org_oid'] = this.selectedDepartment['oid'];
    this.paper['solve_per_pid'] = this.malDepPerson['pid'];
    this.paper['solve_per'] = this.malDepPerson['oid'];
    this.paper['sid'] = this.sid;
    this.submitPost(this.paper);
  }
}
